package com.zx.sercurity;

import android.content.Context;

import com.zx.sercurity.util.BatteryUtil;
import com.zx.sercurity.util.ChargingStateListener;

/**
 * 充电风控
 * 持续充电两小时将会触发风控
 */
public class ChargingRiskCountDown extends CountDownAsyncRiskControl<Void> implements ChargingStateListener, Runnable {

    private static final long CHARGING_HOLDER_MS = 2 * 60 * 60 * 1000; // 2 小时

    private BatteryUtil batteryUtil;
    private boolean batteryIsCharging;
    private AsyncResultWrapper<Void> resultWrapper = new AsyncResultWrapper<>(ProcessState.IDLE,false,riskType(),null);

    public ChargingRiskCountDown(AsyncRiskListener riskLiveData) {
        super(riskLiveData);
    }

    @Override
    public RiskEnum riskType() {
        return RiskEnum.ChargingRisk;
    }

    @Override
    protected long riskHolderTime() {
        return CHARGING_HOLDER_MS;
    }

    @Override
    protected boolean startUp(Context context) {
        if (batteryUtil == null){
            batteryUtil = new BatteryUtil(context);
            batteryUtil.register(this);
        }
        batteryIsCharging = BatteryUtil.isBatteryCharging(context);
        if (listener != null){
            resultWrapper = resultWrapper.newState(ProcessState.RUNNING);
            listener.onAsyncRiskStateChange(resultWrapper);
        }
        return batteryIsCharging;
    }

    @Override
    protected void startUpCanceled() {
        if (listener != null){
            resultWrapper = resultWrapper.newState(ProcessState.STOP);
            listener.onAsyncRiskStateChange(resultWrapper);
        }
    }

    @Override
    protected Runnable onCountDownTrigger() {
        return this;
    }

    @Override
    public void onStatePowerConnected() {
        if (!batteryIsCharging) {
            batteryIsCharging = true;
            resetCountdown();
            if (listener != null){
                resultWrapper = resultWrapper.newState(ProcessState.RUNNING);
                listener.onAsyncRiskStateChange(resultWrapper);
            }
        }
    }

    @Override
    public void onStatePowerDisconnected() {
        if (batteryIsCharging) {
            batteryIsCharging = false;
            stopCountdown();
            if (listener != null){
                resultWrapper = resultWrapper.newState(ProcessState.STOP);
                listener.onAsyncRiskStateChange(resultWrapper);
            }
        }
    }

    @Override
    public void destroy() {
        super.destroy();
        if (batteryUtil != null){
            batteryUtil.unregister();
            batteryUtil = null;
        }
        if (listener != null){
            resultWrapper = resultWrapper.newState(ProcessState.DESTROY);
            listener.onAsyncRiskStateChange(resultWrapper);
        }
    }

    @Override
    public void run() {
        if (listener != null){
            resultWrapper = resultWrapper.inRisk(true);
            listener.onFindAsyncRisk(resultWrapper);
        }
    }
}

